using AutoMapper;
using B.S.Data.ERP.API.Applications.DingDanCommands;
using ERP.Domain;
using ERP.infratrctrue;
using ERP.Requst;
using MediatR;

namespace B.S.Data.ERP.API.Applications.DingDanHandlers
{
    public class AddDingDanCommandHandler : IRequestHandler<AddDingDanCommand, APIRequust<int>>
    {
        private readonly IBaseRepository<DingDan> _dingDanRepository;
        private readonly IMapper _mapper;

        public AddDingDanCommandHandler(IBaseRepository<DingDan> dingDanRepository, IMapper mapper)
        {
            _dingDanRepository = dingDanRepository;
            _mapper = mapper;
        }

        public async Task<APIRequust<int>> Handle(AddDingDanCommand request, CancellationToken cancellationToken)
        {
            var response = new APIRequust<int>();
            try
            {
                // 使用AutoMapper映射命令到实体
                var dingDan = _mapper.Map<DingDan>(request);
                
                // 添加到仓储
                await _dingDanRepository.Add(dingDan);
                
                response.Code = RequstCode.成功;
                response.Msg = RequstCode.成功.ToString();
                response.Data = 1;
            }
            catch (Exception ex)
            {
                response.Code = RequstCode.失败;
                response.Msg = "添加订单失败：" + ex.Message;
                response.Data = 0;
            }
            return response;
        }
    }
}